recSale = new Object();

// custom Vtype for vtype:'Rate'
Ext.apply(Ext.form.field.VTypes, {
	Rate : function(v) {
		return /^100(\.0{0,2})? *%?$|^\d{1,2}(\.\d{1,2})? *%?$/.test(v);
	},
	RateText : 'Invalid Rate',
	RateMask : /[\d\.%]/i
});

var searchResultStore = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'dealCode', 'fund', 'instrumentType', 'insId', 'purchDeal', 'valueDate', 'buyer', 'secMarket', 'secBuyerName', 'secBuyerBankAc', 'settlementCode',
			'delevarymethode', 'dealerCode', 'sellingValue', 'sellingRate', 'placementFee', 'partialSale', 'sellingAmount', 'user' ]
});

var recSaleInsStore = Ext.create('Ext.data.Store', {
	fields : [ {
		name : 'id',
		type : 'int'
	}, {
		name : 'instrumentCode',
		type : 'string'
	} ],
	storeId : 'recSaleInsStore',
});

var recSalePrevPurchStore = Ext.create('Ext.data.Store', {
	fields : [ {
		name : 'id',
		type : 'int'
	}, {
		name : 'dealCode',
		type : 'string'
	}, {
		name : 'dealName',
		type : 'string'
	}, ],
	storeId : 'recSalePrevPurchStore',
});

recSale.getSearchBar = function() {

	return Ext.create('Ext.form.FieldContainer', {
		items : [ {
			xtype : 'triggerfield',
			id : 'recSaleTrigField',
			triggerCls : 'x-form-search-trigger',
			anchor : '28%',
			style : 'float:right;',
			emptyText : 'Search for a Purchase',
			onTriggerClick : function() {
				var searchResult = Ext.create('Ext.data.Store', {
					fields : [ 'id', 'dealCode', 'issuer', 'status' ]
				});
				var TrigField = Ext.ComponentQuery.query('#recSaleTrigField')[0];

				Ext.Ajax.request({
					url : 'getSales.action',
					params : {
						queryOne : TrigField.getValue(),
					},
					success : function(response) {
						var obj = Ext.decode(response.responseText);
						var arrayLength = obj.deals.length;
						for (var i = 0; i < arrayLength; i++) {
							searchResult.add({
								id : obj.deals[i].id,
								dealCode : obj.deals[i].dealCode,
								issuer : obj.deals[i].issuer.code,
								name : obj.deals[i].name,
								status : obj.deals[i].status,
							});
						}
					}
				});

				var resultWindow = Ext.create('Ext.grid.Panel', {
					defaults : {
						anchor : '100%'
					},
					store : searchResult,
					columns : [ {
						text : 'Deal Code',
						dataIndex : 'dealCode',
						flex : 1
					}, {
						text : 'Issuer',
						dataIndex : 'issuer',
						flex : 1
					}, {
						text : 'Status',
						dataIndex : 'status',
						flex : 1
					} ],

					listeners : {
						itemdblclick : function(view, rec, item, index, eventObj) {
							var findId = rec.get('id');
							var formPanl = Ext.ComponentQuery.query('#recSaleFormPanel')[0];
							formPanl.setLoading('Receiving data...', formPanl.getForm());
							var confirmFields = '';
							var updateBtn = Ext.getCmp('recSaleUpdateBtn');
							var saveBtn = Ext.getCmp('recSaleSaveBtn');

							formPanl.getForm().reset();

							Ext.Ajax.request({
								url : 'getSale.action',
								params : {
									id : findId,
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									searchResultStore.loadRawData(obj.saleDealDtos);
									var recor = searchResultStore.getAt(0);
									Ext.Ajax.request({
										url : 'getInstrumById.action',
										params : {
											'instrumentId' : recor.get('insId')
										},
										success : function(response) {
											var obj = Ext.decode(response.responseText);
											recSaleInsStore.loadRawData(obj.instrumentDtos);
										},
										failure : function(form, action) {
											formPanl.setLoading(false);
											Ext.Msg.alert("An Error occured. Load failed");
										}
									});

									Ext.Ajax.request({
										url : 'getPurchdealById.action',
										params : {
											purchDeal : recor.get('purchDeal')
										},
										success : function(response) {
											var obj = Ext.decode(response.responseText);
											if (obj.queryTwo != null && obj.queryTwo != '') {
												var purchArray = obj.queryTwo.split(";");
												var purchStoreLocal = Ext.data.StoreManager.lookup('recSalePrevPurchStore');
												purchStoreLocal.removeAll();
												var i = 0;
												for (i = 0; i < purchArray.length - 1; i++) {
													var purchDealArr = purchArray[i].split(",");
													purchStoreLocal.add({
														id : purchDealArr[0],
														dealCode : purchDealArr[1],
														dealName : purchDealArr[2]
													});
												}
												purchStoreLocal.sort('id', 'ASC');
												formPanl.loadRecord(recor);
												Ext.getCmp('recSaleDealCode').setText('Deal Code: ' + recor.get('dealCode'));
												Ext.getCmp('recSalePurchDealCmb').setValue(recor.get('purchDeal'));
												if (rec.get('status') == 'Initial') {
													updateBtn.enable();
													saveBtn.disable();
												} else {
													updateBtn.disable();
													saveBtn.disable();
												}
												formPanl.setLoading(false);
											}
										},
										failure : function(response) {
											Ext.Msg.alert('Error!', 'Failed to load Previous Purchase Deal List : ' + response);
										},
									});
								},
								failure : function(form, action) {
									formPanl.setLoading(false);
									Ext.Msg.alert("An Error occured. Load failed");
								}
							});
							this.up('.window').close();
							Ext.ComponentQuery.query('#recSaleTrigField')[0].enable();

						}
					}
				});

				Ext.create('Ext.window.Window', {
					title : 'Sales',
					id : 'recSaleResWindow',
					height : 330,
					frame : true,
					width : 500,
					constrain : true,
					resizable : false,
					layout : {
						type : 'fit'
					},
					items : [ resultWindow ]
				}).show();
			}
		} ]
	});
};

recSale.getFieldSet1 = function() {

	var recSaleInsTypes = Ext.create('Ext.data.Store', {
		fields : [ {
			name : 'id',
			type : 'int',
		}, {
			name : 'instrumentName',
			type : 'string',
		}, {
			name : 'istrumentType',
			type : 'string',
		} ],
		storeId : 'recSaleInsTypeStore',
	});

	var recSaleFundStore = Ext.create('Ext.data.Store', {
		fields : [ {
			name : 'id',
			type : 'int',
		}, {
			name : 'fundName',
			type : 'string',
		}, {
			name : 'fundCode',
			type : 'string',
		} ],
	});

	Ext.Ajax.request({
		url : 'getFundsForDeal.action',
		params : {
			querry : 'SALE',
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			recSaleFundStore.loadRawData(obj.fundList);
		}
	});

	var selectInsComboBox = Ext.create('Ext.form.ComboBox', {
		name : 'insId',
		fieldLabel : 'Instrument Code',
		id : 'recSaleInsCodeCmb',
		store : recSaleInsStore,
		queryMode : 'local',
		valueField : 'id',
		displayField : 'instrumentCode',
		autoScroll : true,
		allowBlank : false,
		flex : 1,
		editable : false,
		padding : '0 5 0 5',
		style : 'margin-top:5px;',
		blankText : 'Please select an Instrument to proceed',
		msgTarget : 'under',
		listeners : {
			select : {
				fn : function(combo, value) {
					Ext.Ajax.request({
						url : 'prevPurchases.action',
						params : {
							queryOne : combo.getValue(),
						},
						success : function(response) {
							var obj = Ext.decode(response.responseText);
							if (obj.queryTwo != null && obj.queryTwo != '') {
								var purchArray = obj.queryTwo.split(";");
								var purchStoreLocal = Ext.data.StoreManager.lookup('recSalePrevPurchStore');
								purchStoreLocal.removeAll();
								var i = 0;
								for (i = 0; i < purchArray.length - 1; i++) {
									var purchDealArr = purchArray[i].split(",");
									purchStoreLocal.add({
										id : purchDealArr[0],
										dealCode : purchDealArr[1],
										dealName : purchDealArr[2]
									});
								}
								purchStoreLocal.sort('id', 'ASC');
							}
						},
						failure : function(response) {
							Ext.Msg.alert('Error!', 'Failed to load Previous Purchase Deal List : ' + response);
						},
					});
				}
			}
		}

	});

	var recSaleIssuerStore = Ext.create('Ext.data.Store', {
		fields : [ {
			name : 'id',
			type : 'int',
		}, {
			name : 'name',
			type : 'string',
		}, {
			name : 'code',
			type : 'string',
		} ],
		storeId : 'recSaleIssuerStore',
	});

	Ext.Ajax.request({
		url : 'getIssuers.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			recSaleIssuerStore.loadRawData(obj.issuerList);
		},
		failure : function(response) {
			Ext.Msg.alert('Error!', 'Failed to Load Issuers!');
		}

	});

	var selectBuyerComboBox = Ext.create('Ext.form.ComboBox', {
		name : 'buyer',
		fieldLabel : 'Buyer',
		id : 'recSaleIssuerCmb',
		store : recSaleIssuerStore,
		queryMode : 'local',
		valueField : 'id',
		autoScroll : true,
		allowBlank : false,
		flex : 1,
		padding : '0 5 0 5',
		style : 'margin-top:5px;',
		blankText : 'Please select an Issuer to proceed',
		msgTarget : 'under',
		editable : false,
		tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name} - <b>{code}</b><br/></div>', '</tpl>'),
		displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>'),
	});

	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'Basic',
		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'label',
			id : 'recSaleDealCode',
			style : 'font-weight:600;margin-top:7px;',
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ Ext.create('Ext.form.ComboBox', {
				name : 'fund',
				id : 'recSaleFundCmb',
				fieldLabel : 'Fund',
				store : recSaleFundStore,
				valueField : 'id',
				autoScroll : true,
				allowBlank : false,
				queryMode : 'local',
				flex : 1,
				padding : '0 5 0 5',
				blankText : 'Please select a Fund to proceed',
				msgTarget : 'under',
				editable : false,
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{fundName} - <b>{fundCode}</b><br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{fundName}', '</tpl>'),
				listeners : {
					select : {
						fn : function(combo, value) {
							Ext.ComponentQuery.query('#recSaleInsTypeCmb')[0].clearValue();
							Ext.ComponentQuery.query('#recSaleInsCodeCmb')[0].clearValue();
							recSaleInsStore.removeAll();
							recSaleInsTypes.removeAll();
							Ext.Ajax.request({
								url : 'dealInsTypes.action',
								params : {
									queryOne : combo.getValue(),
									queryTwo : 'SALE',
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									Ext.data.StoreManager.lookup('recSaleInsTypeStore').loadRawData(obj.insTypeList);
								},
								failure : function(response) {
									Ext.Msg.alert('Error!', 'Failed to Load Instrument Types!');
								}
							});
						}
					},
					change : function(list, record) {
						Ext.Ajax.request({
							url : 'dealInsTypes.action',
							params : {
								queryOne : list.getValue(),
								queryTwo : 'SALE',
							},
							success : function(response) {
								var obj = Ext.decode(response.responseText);
								Ext.data.StoreManager.lookup('recSaleInsTypeStore').loadRawData(obj.insTypeList);
							},
							failure : function(response) {
								Ext.Msg.alert('Error!', 'Failed to Load Instrument Types!');
							}
						});
					}
				}
			}), Ext.create('Ext.form.ComboBox', {
				name : 'instrumentType',
				fieldLabel : 'Instrument Type',
				id : 'recSaleInsTypeCmb',
				store : recSaleInsTypes,
				queryMode : 'local',
				valueField : 'id',
				displayField : 'instrumentName',
				autoScroll : true,
				allowBlank : false,
				flex : 1,
				padding : '0 5 0 5',
				blankText : 'Please select an Instrument Type to proceed',
				msgTarget : 'under',
				editable : false,
				listeners : {
					select : {
						fn : function(combo, value) {
							var govLbl = Ext.ComponentQuery.query('#recSaleGovLbl')[0];
							var issuerCmb = Ext.ComponentQuery.query('#recSaleIssuerCmb')[0];
							Ext.ComponentQuery.query('#recSaleInsCodeCmb')[0].clearValue();
							recSaleInsStore.removeAll();
							Ext.Ajax.request({
								url : 'InsFromTypes.action',
								params : {
									queryOne : combo.getValue(),
									queryTwo : Ext.ComponentQuery.query('#recSaleFundCmb')[0].getValue(),
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									Ext.data.StoreManager.lookup('recSaleInsStore').loadRawData(obj.insList);
									var insTypesStoreTmp = Ext.data.StoreManager.lookup('recSaleInsTypeStore');
									if (insTypesStoreTmp.getAt(insTypesStoreTmp.find('id', combo.getValue())).get('istrumentType') === 'G') {
										govLbl.setText('Issuer Type: Government');
										issuerCmb.clearValue();
									} else {
										govLbl.setText('Issuer Type: Non-Government');
									}
								},
								failure : function(response) {
									Ext.Msg.alert('Error!', 'Failed to Load Instruments!');
								}
							});
						}
					}
				}
			}) ]
		}, {
			xtype : 'label',
			id : 'recSaleDealStatus',
			style : 'font-weight:600;margin-top:7px;',
		},

		{
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ selectInsComboBox, Ext.create('Ext.form.ComboBox', {
				name : 'purchDeal',
				fieldLabel : 'Purchase Deal',
				id : 'recSalePurchDealCmb',
				store : recSalePrevPurchStore,
				queryMode : 'local',
				valueField : 'id',
				autoScroll : true,
				allowBlank : false,
				flex : 1,
				padding : '0 5 0 5',
				style : 'margin-top:5px;',
				blankText : 'Please select an Instrument Type to proceed',
				msgTarget : 'under',
				editable : false,
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item"><b>{dealCode}</b> - {dealName}<br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{dealCode}', '</tpl>'),
				listeners : {
					select : {
						fn : function(combo, value) {
							console.log(combo.getValue());
							Ext.Ajax.request({
								url : 'prevPurch.action',
								params : {
									queryOne : combo.getValue(),
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									Ext.ComponentQuery.query('#recSalePreValue')[0].setValue(obj.preDealVal);
									Ext.ComponentQuery.query('#recSalePreIssuer')[0].setValue(obj.preIssuer);
									if (obj.preSecMarket) {
										Ext.ComponentQuery.query('#recSalePreSecMarket')[0].setValue(true);
										if (obj.preSecSeller != null) {
											Ext.ComponentQuery.query('#recSalePreSecSeller')[0].setValue(obj.preSecSeller);
										} else {
											Ext.ComponentQuery.query('#recSalePreSecSeller')[0].reset();
										}
									} else {
										Ext.ComponentQuery.query('#recSalePreSecMarket')[0].setValue(false);
										Ext.ComponentQuery.query('#recSalePreSecSeller')[0].reset();
									}
									if (obj.preCpnRate != null) {
										Ext.ComponentQuery.query('#recSaleCouponRate')[0].setValue(obj.preCpnRate);
										if (obj.preCpnDateFixed) {
											Ext.ComponentQuery.query('#recSaleCpnFixcb')[0].setValue(true);
										} else {
											Ext.ComponentQuery.query('#recSaleCpnVarycb')[0].setValue(true);
										}
									} else {
										Ext.ComponentQuery.query('#recSaleCouponRate')[0].reset();
										Ext.ComponentQuery.query('#recSaleCpnFixcb')[0].reset();
										Ext.ComponentQuery.query('#recSaleCpnVarycb')[0].reset();
									}

									if (obj.preInterestFixed) {
										Ext.ComponentQuery.query('#recSaleIntTypeFix')[0].setValue(true);
									} else {
										Ext.ComponentQuery.query('#recSaleIntTypeFloat')[0].setValue(true);
									}

									if (obj.preInterestStraight) {
										Ext.ComponentQuery.query('#recSaleIntStraight')[0].setValue(true);
									} else {
										Ext.ComponentQuery.query('#recSaleIntDiscount')[0].setValue(true);
									}
									if (obj.sellingAmount != null) {
										Ext.ComponentQuery.query('#recSaleSellingAmount')[0].setValue(obj.sellingAmount);
									}

									if (obj.preScripts) {
										Ext.ComponentQuery.query('#recSaleScript')[0].setValue(true);
									} else {
										Ext.ComponentQuery.query('#recSaleScript')[0].setValue(false);
									}

									if (obj.preDenominals) {
										Ext.ComponentQuery.query('#recSaleDen')[0].setValue(true);
										Ext.ComponentQuery.query('#recSalePartialSale')[0].setValue(false);
										Ext.ComponentQuery.query('#recSalePartialSale')[0].enable();
										if (obj.preDenMinVal != null) {
											Ext.ComponentQuery.query('#recSaleDenMinVal')[0].setValue(obj.preDenMinVal);
										}
									} else {
										Ext.ComponentQuery.query('#recSaleDen')[0].setValue(false);
										Ext.ComponentQuery.query('#recSaleDenMinVal')[0].reset();
										Ext.ComponentQuery.query('#recSalePartialSale')[0].setValue(false);
										Ext.ComponentQuery.query('#recSalePartialSale')[0].disable();
									}

									Ext.ComponentQuery.query('#recSalePreRate')[0].setValue(obj.preRate);
									Ext.ComponentQuery.query('#recSalePreDealCode')[0].setText('Purchase Deal Code: ' + obj.preDealCode);

								},
								failure : function(response) {
									Ext.Msg.alert('Error!', 'Failed to Load Purchase Details!');
								}
							});
						}
					},
					change : function(list, record) {
						if (record) {
							Ext.Ajax.request({
								url : 'prevPurch.action',
								params : {
									queryOne : list.getValue(),
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									Ext.ComponentQuery.query('#recSalePreValue')[0].setValue(obj.preDealVal);
									Ext.ComponentQuery.query('#recSalePreIssuer')[0].setValue(obj.preIssuer);
									if (obj.preSecMarket) {
										Ext.ComponentQuery.query('#recSalePreSecMarket')[0].setValue(true);
										if (obj.preSecSeller != null) {
											Ext.ComponentQuery.query('#recSalePreSecSeller')[0].setValue(obj.preSecSeller);
										} else {
											Ext.ComponentQuery.query('#recSalePreSecSeller')[0].reset();
										}
									} else {
										Ext.ComponentQuery.query('#recSalePreSecMarket')[0].setValue(false);
										Ext.ComponentQuery.query('#recSalePreSecSeller')[0].reset();
									}
									if (obj.preCpnRate != null) {
										Ext.ComponentQuery.query('#recSaleCouponRate')[0].setValue(obj.preCpnRate);
										if (obj.preCpnDateFixed) {
											Ext.ComponentQuery.query('#recSaleCpnFixcb')[0].setValue(true);
										} else {
											Ext.ComponentQuery.query('#recSaleCpnVarycb')[0].setValue(true);
										}
									} else {
										Ext.ComponentQuery.query('#recSaleCouponRate')[0].reset();
										Ext.ComponentQuery.query('#recSaleCpnFixcb')[0].reset();
										Ext.ComponentQuery.query('#recSaleCpnVarycb')[0].reset();
									}

									if (obj.preInterestFixed) {
										Ext.ComponentQuery.query('#recSaleIntTypeFix')[0].setValue(true);
									} else {
										Ext.ComponentQuery.query('#recSaleIntTypeFloat')[0].setValue(true);
									}

									if (obj.preInterestStraight) {
										Ext.ComponentQuery.query('#recSaleIntStraight')[0].setValue(true);
									} else {
										Ext.ComponentQuery.query('#recSaleIntDiscount')[0].setValue(true);
									}
									if (obj.sellingAmount != null) {
										Ext.ComponentQuery.query('#recSaleSellingAmount')[0].setValue(obj.sellingAmount);
									}

									if (obj.preScripts) {
										Ext.ComponentQuery.query('#recSaleScript')[0].setValue(true);
										if (obj.preDenominals) {
											Ext.ComponentQuery.query('#recSaleDen')[0].setValue(true);
											Ext.ComponentQuery.query('#recSalePartialSale')[0].setValue(false);
											Ext.ComponentQuery.query('#recSalePartialSale')[0].enable();
											if (obj.preDenMinVal != null) {
												Ext.ComponentQuery.query('#recSaleDenMinVal')[0].setValue(obj.preDenMinVal);
											}
										} else {
											Ext.ComponentQuery.query('#recSaleDen')[0].setValue(false);
											Ext.ComponentQuery.query('#recSaleDenMinVal')[0].reset();
											Ext.ComponentQuery.query('#recSalePartialSale')[0].setValue(false);
											Ext.ComponentQuery.query('#recSalePartialSale')[0].disable();
										}
									} else {
										Ext.ComponentQuery.query('#recSaleScript')[0].setValue(false);
										Ext.ComponentQuery.query('#recSaleDen')[0].setValue(false);
										Ext.ComponentQuery.query('#recSaleDenMinVal')[0].reset();
										Ext.ComponentQuery.query('#recSalePartialSale')[0].enable();
										Ext.ComponentQuery.query('#recSalePartialSale')[0].setValue(false);
									}

									Ext.ComponentQuery.query('#recSalePreRate')[0].setValue(obj.preRate);
									Ext.ComponentQuery.query('#recSalePreDealCode')[0].setText('Purchase Deal Code: ' + obj.preDealCode);

								},
								failure : function(response) {
									Ext.Msg.alert('Error!', 'Failed to Load Purchase Details!');
								}
							});
						}
					}
				}
			}) ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'datefield',
				fieldLabel : 'Value Date',
				id : 'recSaleValDate',
				allowBlank : false,
				flex : 1,
				name : 'valueDate',
				padding : '0 5 0 5',
				style : 'margin-top:5px;',
				blankText : 'Please select a Start Date',
				msgTarget : 'under',
				format : 'd/m/Y',
				submitFormat : 'd/m/Y',
				emptyText : 'dd/mm/yyyy',
				listeners : {
					'change' : {
						fn : function(field, newVal, oldVal) {
							recSale.setSellingValByMaturity();
						}
					}
				}
			}, selectBuyerComboBox ]
		}, {
			xtype : 'label',
			id : 'recSaleGovLbl',
			text : 'Issuer Type:',
			padding : '0 5 0 5',
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'checkboxfield',
				boxLabel : 'Secondary Market',
				name : 'secMarket',
				id : 'recSaleSecMarket',
				padding : '0 5 0 5',
				style : 'margin-top:5px;',
				inputValue : '1',
				listeners : {
					change : {
						fn : function(object, Value) {
							var buyername = Ext.ComponentQuery.query('#recSaleBuyerName')[0];
							var buyerBankAc = Ext.ComponentQuery.query('#recSaleBuyerBankAc')[0];
							if (Value) {
								buyername.enable();
								buyerBankAc.enable();
							} else {
								buyername.reset();
								buyername.disable();
								buyerBankAc.reset();
								buyerBankAc.disable();
							}
						}
					}
				}
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				name : 'secBuyerName',
				allowBlank : false,
				id : 'recSaleBuyerName',
				flex : 1,
				padding : '0 5 0 5',
				style : 'margin-top:5px;',
				fieldLabel : "Buyer's Name",
				disabled : true
			}, {
				xtype : 'textfield',
				name : 'secBuyerBankAc',
				allowBlank : false,
				flex : 1,
				style : 'margin-top:5px;',
				padding : '0 5 0 5',
				id : 'recSaleBuyerBankAc',
				fieldLabel : "Bank Account",
				disabled : true
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'combo',
				fieldLabel : 'Delevary Method',
				store : CommenStore.delevaryMethodStore,
				valueField : 'id',
				flex : 1,
				labelWidth : 120,
				name : 'delevarymethode',
				padding : '0 5 0 0',
				displayField : 'code',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{description}</b><br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {description}', '</tpl>'),
				listeners : {
					change : function(combo, record, index) {
						if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
							combo.setValue(null);
						}
					}
				}
			}, {
				xtype : 'combo',
				fieldLabel : 'Dealer',
				store : CommenStore.dealersStore,
				valueField : 'id',
				flex : 1,
				padding : '0 5 0 0',
				name : 'dealerCode',
				displayField : 'code',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{name}</b><br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {name}', '</tpl>'),
				listeners : {
					change : function(combo, record, index) {
						if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
							combo.setValue(null);
						}
					}
				}
			} ]
		}, {
			xtype : 'combo',
			labelWidth : 120,
			fieldLabel : 'Settlement Method',
			store : CommenStore.settlmentStore,
			valueField : 'id',
			anchor : '50%',
			name : 'settlementCode',
			padding : '0 10 0 0',
			displayField : 'code',
			tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{description}</b><br/></div>', '</tpl>'),
			displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {description}', '</tpl>'),
			listeners : {
				change : function(combo, record, index) {
					if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
						combo.setValue(null);
					}
				}
			}
		} ]
	});
	return finalFieldSet;
};

recSale.getFieldSet2 = function() {

	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'Instrument Infomation',
		defaults : {
			labelWidth : 175,
			anchor : '100%'
		},
		items : [ {
			xtype : 'label',
			id : 'recSalePreDealCode',
			style : 'font-weight:600;margin-top:7px;',
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				fieldLabel : 'Purchase Value',
				id : 'recSalePreValue',
				padding : '0 5 0 0',
				disabled : true,
				flex : 1
			}, {
				xtype : 'textfield',
				id : 'recSalePreIssuer',
				fieldLabel : "Issuer",
				flex : 1,
				disabled : true
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'checkboxfield',
				boxLabel : 'Secondary Market',
				padding : '0 5 5 5',
				flex : 1,
				disabled : true,
				id : 'recSalePreSecMarket',
			}, {
				xtype : 'textfield',
				name : 'secSellerName',
				id : 'recSalePreSecSeller',
				fieldLabel : "Seller's Name",
				flex : 1,
				padding : '0 5 5 0',
				disabled : true
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				vtype : 'Rate',
				validateOnBlur : true,
				maskRe : /[\d\%.]/,
				flex : 1,
				id : 'recSaleCouponRate',
				fieldLabel : 'Coupon Rate',
				padding : '0 5 5 5',
				disabled : true
			}, {
				xtype : 'fieldcontainer',
				fieldLabel : 'Coupon Dates',
				defaultType : 'checkboxfield',
				layout : 'hbox',
				flex : 1,
				padding : '0 5 5 10',
				disabled : true,
				items : [ {
					boxLabel : 'Fixed',
					id : 'recSaleCpnFixcb',
					padding : '0 5 0 5',
				}, {
					boxLabel : 'Vary',
					id : 'recSaleCpnVarycb',
					padding : '0 5 0 5',
				} ]
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'fieldcontainer',
				fieldLabel : 'Interest Rate',
				layout : 'hbox',
				padding : '0 5 5 5',
				flex : 1,
				disabled : true,
				items : [ {
					xtype : 'radiofield',
					boxLabel : 'Fixed',
					id : 'recSaleIntTypeFix',
					disabled : true,
					padding : '0 5 0 5',
				}, {
					xtype : 'radiofield',
					boxLabel : 'Floating',
					id : 'recSaleIntTypeFloat',
					disabled : true,
					padding : '0 5 0 5',
				} ]
			}, {
				xtype : 'fieldcontainer',
				fieldLabel : 'Calculation',
				layout : 'hbox',
				flex : 1,
				padding : '0 5 5 5',
				disabled : true,
				items : [ {
					xtype : 'radiofield',
					id : 'recSaleIntStraight',
					boxLabel : 'Straight',
					inputValue : 'straight',
					padding : '0 5 0 5',
				}, {
					xtype : 'radiofield',
					id : 'recSaleIntDiscount',
					boxLabel : 'Discounted',
					inputValue : 'discounted',
					padding : '0 5 0 5',
				} ]
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'checkboxfield',
				boxLabel : 'Scripts',
				padding : '5 5 5 5',
				flex : 1,
				id : 'recSaleScript',
				disabled : true,
			}, {
				xtype : 'textfield',
				fieldLabel : 'Rate',
				vtype : 'Rate',
				validateOnBlur : true,
				maskRe : /[\d\%.]/,
				padding : '5 5 5 0',
				flex : 1,
				id : 'recSalePreRate',
				disabled : true,
				listeners : {
					blur : function() {
						var value = Ext.util.Format.number(this.value.replace(/%/g, ''), '000.00');
						this.setRawValue(value + "%");
					}
				}
			}

			]
		}, , {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'checkboxfield',
				boxLabel : 'Denominals',
				padding : '0 5 5 5',
				flex : 1,
				id : 'recSaleDen',
				disabled : true,

			}, {
				xtype : 'textfield',
				fieldLabel : 'Minimum Value',
				padding : '0 5 5 0',
				flex : 1,
				id : 'recSaleDenMinVal',
				disabled : true,
			}

			]
		} ]
	});
	return finalFieldSet;
};

recSale.getFieldSet3 = function() {

	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'Sale Information',
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'checkboxfield',
				boxLabel : 'Partial Sale',
				flex : 1,
				name : 'partialSale',
				id : 'recSalePartialSale',
				inputValue : true,
				disabled : true,
				listeners : {
					change : function(field, newVal) {
						if (newVal) {
							Ext.ComponentQuery.query('#recSaleSellingAmount')[0].enable();
						} else {
							Ext.ComponentQuery.query('#recSaleSellingAmount')[0].disable();
						}
					}
				}
			}, {
				xtype : 'textfield',
				fieldLabel : 'Selling Amount',
				flex : 1,
				id : 'recSaleSellingAmount',
				name : 'sellingAmount',
				disabled : true,
				allowBlank : false,
				listeners : {
					blur : function() {
						this.setRawValue(Ext.util.Format.number(this.value.replace(/,/g, ''), '0,000.0000'));
						if (Ext.ComponentQuery.query('#recSaleDen')[0].getValue()) {
							if (Ext.ComponentQuery.query('#recSaleDen')[0].getValue() != null && Ext.ComponentQuery.query('#recSaleDen')[0].getValue() != 'null') {
								if (this.value.replace(/,/g, '') % Ext.ComponentQuery.query('#recSaleDenMinVal')[0].getValue().replace(/,/g, '') != 0) {
									Ext.Msg.alert('Error', 'Selling Value should be a multiple of Denominals');
									this.reset();
								}
							}
						}
					},
					render : function(p) {
						this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
					}
				}
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				id : 'recSaleSellingVal',
				minValue : 0,
				name : 'sellingValue',
				fieldLabel : 'Selling Value',
				allowBlank : false,
				blankText : 'Please enter the Deal Amount',
				msgTarget : 'under',
				flex : 1,
				readOnly : true,
				padding : '0 5 5 0',
				maskRe : /[\d\,.]/,
				listeners : {
					blur : function() {
						this.setRawValue(Ext.util.Format.number(this.value.replace(/,/g, ''), '0,000.0000'));
					},
					render : function(p) {
						this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
					}
				}
			}, {
				xtype : 'textfield',
				vtype : 'Rate',
				validateOnBlur : true,
				maskRe : /[\d\%.]/,
				id : 'recSaleSallingRate',
				flex : 1,
				padding : '0 5 5 0',
				name : 'sellingRate',
				fieldLabel : 'Selling Rate',
				listeners : {
					blur : function() {
						var value = Ext.util.Format.number(this.value.replace(/%/g, ''), '000.00');
						this.setRawValue(value + "%");
						recSale.setSellingValByMaturity();
					}
				}
			} ]
		}, {
			xtype : 'textfield',
			minValue : 0,
			id : 'recSalePlacementFee',
			name : 'placementFee',
			fieldLabel : 'Placement Fee',
			allowBlank : false,
			blankText : 'Please enter the Placement Fee',
			msgTarget : 'under',
			flex : 1,
			anchor : '50%',
			padding : '0 5 5 0',
			maskRe : /[\d\,.]/,
			listeners : {
				blur : function() {
					this.setRawValue(Ext.util.Format.number(this.value.replace(/,/g, ''), '0,000.0000'));
				},
				render : function(p) {
					this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
				}
			}
		} ]
	});
	return finalFieldSet;
};

recSale.getCenterPanel = function() {
	var filedset1 = recSale.getFieldSet1();
	var filedset2 = recSale.getFieldSet2();
	var filedset3 = recSale.getFieldSet3();
	var searchBar = recSale.getSearchBar();

	CommenStore.settlmentStore.load();
	CommenStore.dealersStore.load();
	CommenStore.delevaryMethodStore.load();

	var formPanel = Ext.create('Ext.form.FormPanel', {
		bodyPadding : '20',
		id : 'recSaleFormPanel',
		autoScroll : true,
		frame : true,
		defaults : {
			labelWidth : 175,
			anchor : '68%',
		},
		fieldDefaults : {
			labelAlign : 'left',
			labelWidth : 150,
		},
		title : 'Record SALE',
		items : [ searchBar, filedset1, filedset2, filedset3 ],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				this.up('form').getForm().reset();
				Ext.ComponentQuery.query('#recSaleDealCode')[0].setText('');
				Ext.ComponentQuery.query('#recSaleDealStatus')[0].setText('');
				Ext.ComponentQuery.query('#recSalePreDealCode')[0].setText('');
				Ext.ComponentQuery.query('#recSaleGovLbl')[0].setText('');
				// Ext.ComponentQuery.query('#recSalePreDealCode')[0].setText('');
				Ext.getCmp('recSaleSaveBtn').disable();
				Ext.getCmp('recSaleUpdateBtn').disable();
				Ext.ComponentQuery.query('#recSaleFundCmb')[0].enable();
				Ext.ComponentQuery.query('#recSaleInsTypeCmb')[0].enable();
				Ext.ComponentQuery.query('#recSaleInsCodeCmb')[0].enable();
				// Ext.data.StoreManager.lookup('couponDatesStore').removeAll();
				App.Core.setScreen(recSale.getCenterPanel());
			}
		}, {
			text : 'Save',
			id : 'recSaleSaveBtn',
			itemId : 'saveButton',
			handler : function() {
				var form = this.up('form').getForm();
				form.url = 'newSale.action';
				if (form.isValid()) {
					formPanel.setLoading('Saving...');
					var valueDtField = Ext.ComponentQuery.query('#recSaleValDate')[0];
					form.submit({
						params : {
							'user' : 'createdUser',
							'valueDate' : Ext.util.Format.date(valueDtField.getValue()),
						},
						success : function(form, action) {
							form.reset();
							Ext.Msg.alert('Success', action.result.name + ' is created.<br> Deal Code is <b>' + action.result.dealCode + '</b>');
							Ext.ComponentQuery.query('#recSaleGovLbl')[0].setText('');
							Ext.ComponentQuery.query('#recSalePreDealCode')[0].setText('');
							formPanel.setLoading(false);
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', 'There is some error returned from the server.<br>' + action.result.status);
							formPanel.setLoading(false);
						}
					});
				} else {
					Ext.Msg.alert("Form Incomplete. Please check!");
				}
			}

		}, {
			text : 'Update',
			id : 'recSaleUpdateBtn',
			itemId : 'updateButton',
			disabled : true,
			handler : function() {
				var form = this.up('form').getForm();
				form.url = 'modifySale.action';
				Ext.ComponentQuery.query('#recSaleFundCmb')[0].enable();
				Ext.ComponentQuery.query('#recSaleInsTypeCmb')[0].enable();
				Ext.ComponentQuery.query('#recSaleInsCodeCmb')[0].enable();
				if (form.isValid()) {
					formPanel.setLoading('Updating...');
					var dealCode = Ext.ComponentQuery.query('#recSaleDealCode')[0].text.substr(11);
					var valueDtField = Ext.ComponentQuery.query('#recSaleValDate')[0];
					console.log(dealCode);
					form.submit({
						params : {
							'user' : 'updatedUser',
							'dealCode' : dealCode,
							'valueDate' : Ext.util.Format.date(valueDtField.getValue()),
						},
						success : function(form, action) {
							form.reset();
							Ext.Msg.alert('Success', action.result.name + ' is created.<br> Deal Code is <b>' + action.result.dealCode + '</b>');
							Ext.ComponentQuery.query('#recSaleDealCode')[0].setText('');
							Ext.ComponentQuery.query('#recSaleDealStatus')[0].setText('');
							Ext.ComponentQuery.query('#recSalePreDealCode')[0].setText('');
							Ext.ComponentQuery.query('#recSaleGovLbl')[0].setText('');
							Ext.ComponentQuery.query('#recSalePreDealCode')[0].setText('');
							Ext.getCmp('recSaleSaveBtn').disable();
							Ext.getCmp('recSaleUpdateBtn').disable();
							Ext.ComponentQuery.query('#recSaleFundCmb')[0].enable();
							Ext.ComponentQuery.query('#recSaleInsTypeCmb')[0].enable();
							Ext.ComponentQuery.query('#recSaleInsCodeCmb')[0].enable();
							formPanel.setLoading(false);
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', 'There is some error returned from the server.<br>' + action.result.status);
							formPanel.setLoading(false);
						}
					});
				} else {
					Ext.Msg.alert("Form Incomplete. Please check!");
				}
			}
		} ]
	});
	return formPanel;
};

recSale.setSellingValByMaturity = function() {

	var insType = Ext.ComponentQuery.query('#recSaleInsTypeCmb')[0].getValue();
	if (insType == null)
		return;

	var instrument = Ext.getCmp('recSaleInsCodeCmb').getValue();
	if (instrument == null)
		return;

	var maturityValueField = Ext.ComponentQuery.query('#recSaleSellingAmount')[0];
	var maturityValue;

	maturityValue = maturityValueField.getValue();
	if (maturityValue == '' || maturityValue == null)
		return;

	var interestRate = Ext.ComponentQuery.query('#recSaleSallingRate')[0].getValue();
	if (interestRate == null || interestRate == '')
		return;

	var valueDt = Ext.ComponentQuery.query('#recSaleValDate')[0].getValue();
	if (valueDt == null)
		return;
	console.log(Ext.util.Format.date(valueDt, 'd/m/Y'));
	var purchaseDeal = Ext.getCmp('recSalePurchDealCmb').getValue();
	if (purchaseDeal == null)
		return;

	console.log('COMPLETED');

	Ext.Ajax.request({
		url : 'evalSaleDealValue.action',
		params : {
			'insId' : instrument,
			'instrumentType' : insType,
			'valueDate' : Ext.util.Format.date(valueDt, 'd/m/Y'),
			'sellingAmount' : maturityValue,
			'purchDeal' : purchaseDeal,
			'sellingRate' : interestRate
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.ComponentQuery.query('#recSaleSellingVal')[0].setValue(Ext.util.Format.number(obj.sellingValue.replace(/,/g, ''), '0,000.00'));
		},
		failure : function(response) {
			alert('Error in Maturity Value Calculation : ' + obj.status);
			Ext.ComponentQuery.query('#recSaleSellingVal')[0].reset();
		}
	});
};